<template>
  <div class="spanControl-list" style="width: 100%;margin-left: 0!important;">
    <el-card class="box-card card-head" style="margin: 0px; width: 100%; min-height: 99%">
      <div slot="header" class="clearfix">
        <span>订单管理</span>
      </div>
      <div class="alert-container clearfix">
        <el-alert v-for="alert in alerts.successes" :key="alert.title"
                  v-bind:title="alert.title"
                  type="success"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.infos" :key="alert.title"
                  v-bind:title="alert.title"
                  type="info"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.warnings" :key="alert.title"
                  v-bind:title="alert.title"
                  type="warning"
                  show-icon>
        </el-alert>
        <el-alert v-for="alert in alerts.errors" :key="alert.title"
                  v-bind:title="alert.title"
                  type="error"
                  show-icon>
        </el-alert>
      </div>
      <div class="text item">
        <el-form ref="orderForm" :model="order" label-width="150px" :rules="rules">
          <!--<el-col :span="11">-->
          <!--<el-form-item label="名称" prop="name">-->
          <!--<file-tip content="名称"></file-tip>-->
          <!--<el-input type="input" v-model="order.name"-->
          <!--placeholder="名称" clearable autosize-->
          <!--resize ="both" tabindex=1-->
          <!--maxlength=255-->
          <!--&gt;</el-input>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="11">
            <el-form-item label="订单编号" prop="orderCode">
              <file-tip content="订单编号"></file-tip>
              <el-input type="input" v-model="order.orderCode"
                        placeholder="订单编号" clearable autosize
                        resize="both" tabindex=3
                        maxlength=20
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="物流编号" prop="logisticsCode">
              <file-tip content="物流编号"></file-tip>
              <el-input type="input" v-model="order.logisticsCode"
                        placeholder="物流编号" clearable autosize
                        resize="both" tabindex=4
                        maxlength=20
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="商家" prop="businessName">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="order.businessName"
                :fetch-suggestions="searchBusinessName "
                placeholder="商家"
                @select="handleSelectBusinessName"
                clearable autosize
                resize="both" tabindex="5"
              ></el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="总价" prop="totalPrice">
              <el-input type="number" step="0.01" v-model="order.totalPrice"
                        placeholder="总价" clearable autosize
                        resize="both" tabindex=6
                        maxlength=255
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="下单时间" prop="orderTime">
              <el-date-picker clearable
                              v-model="order.orderTime"
                              align="right"
                              type="date"
                              placeholder="下单时间"
                              :picker-options="pickerOptionsOrderTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="支付时间" prop="paymentTime">
              <el-date-picker clearable
                              v-model="order.paymentTime"
                              align="right"
                              type="date"
                              placeholder="支付时间"
                              :picker-options="pickerOptionsPaymentTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker clearable
                              v-model="order.updateTime"
                              align="right"
                              type="date"
                              placeholder="更新时间"
                              :picker-options="pickerOptionsUpdateTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="order.orderStatus"
                :fetch-suggestions="searchOrderStatus "
                placeholder="订单状态"
                clearable autosize
                resize="both" tabindex="10"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="收货人姓名" prop="receiverName">
              <file-tip content="收货人姓名"></file-tip>
              <el-input type="input" v-model="order.receiverName"
                        placeholder="收货人姓名" clearable autosize
                        resize="both" tabindex=11
                        maxlength=30
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="收货人电话" prop="receiverTel">
              <file-tip content="收货人电话"></file-tip>
              <el-input type="input" v-model="order.receiverTel"
                        placeholder="收货人电话" clearable autosize
                        resize="both" tabindex=12
                        maxlength=11
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="收货人地址" prop="receiverAddress">
              <file-tip content="收货人地址"></file-tip>
              <el-input type="input" v-model="order.receiverAddress"
                        placeholder="收货人地址" clearable autosize
                        resize="both" tabindex=13
                        maxlength=200
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="订单评价" prop="evaluationName">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="order.evaluationName"
                :fetch-suggestions="searchEvaluationName "
                placeholder="订单评价"
                @select="handleSelectEvaluationName"
                clearable autosize
                resize="both" tabindex="15"
              ></el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="用户" prop="employeeName">
              <el-autocomplete
                class="inline-input"
                value-key="name"
                v-model="order.employeeName"
                :fetch-suggestions="searchEmployeeName "
                placeholder="用户"
                @select="handleSelectEmployeeName"
                clearable autosize
                resize="both" tabindex="16"
              ></el-autocomplete>
            </el-form-item>
          </el-col>

          <!--<el-col :span="22">-->
          <!--<el-form-item label="备注" prop="remark">-->
          <!--<file-tip content="备注"></file-tip>-->
          <!--<el-input type="textarea" v-model="order.remark"-->
          <!--placeholder="备注" clearable autosize-->
          <!--resize ="both" tabindex=10000-->
          <!--maxlength=255-->
          <!--&gt;</el-input>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
          <el-col :span="11">
            <el-form-item>
              <el-button type="primary" @click="submitOrder()" :loading="isSubmiting"
                         v-permission:simple_order_Order_Edit>提交
              </el-button>
              <el-button type="primary" @click="backPage" style="background: #CC3300">取消
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="text item clearfix">
        <el-alert v-for="remark in alerts.remarks" :key="remark.title"
                  v-bind:title="remark.title"
                  type="info"
                  v-bind:description="remark.content">
        </el-alert>
      </div>
    </el-card>
  </div>
</template>

<script>


  import {BusinessService} from '../../simple/businessRegistration/BusinessService'
  import {EvaluationService} from '../../simple/evaluation/EvaluationService'
  import {EmployeeService} from '../../simple/organization/EmployeeService'
  import {OrderService} from './OrderService'
  import {d4utils} from '../../../tools/d4utils'
  import fileTip from '@/components/tip/fileTip'

  export default {
    components: {
      fileTip
    },
    data() {
      var validateIntRange = d4utils.validateFloatRange;
      var validateFloatRange = d4utils.validateFloatRange;
      var validateString = d4utils.validateString;

      return {
        rules: {
          name: [
            {required: false, message: '请输入名称', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          orderCode: [
            {required: true, message: '请输入订单编号', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          logisticsCode: [
            {required: false, message: '请输入物流编号', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          businessId: [
            {required: false, message: '请输入商家', trigger: 'blur'},
          ],
          businessName: [
            {required: false, message: '请输入商家', trigger: 'blur'},
          ],
          totalPrice: [
            {required: false, message: '请输入总价', trigger: 'blur'},
            {validator: validateFloatRange(-9223372036854775808, 9223372036854775807), trigger: 'blur'},
          ],
          orderTime: [
            {type: 'date', required: false, message: '请输入下单时间', trigger: 'change'},
          ],
          paymentTime: [
            {type: 'date', required: false, message: '请输入支付时间', trigger: 'change'},
          ],
          updateTime: [
            {type: 'date', required: false, message: '请输入更新时间', trigger: 'change'},
          ],
          orderStatus: [
            {required: false, message: '请输入订单状态', trigger: 'blur'},
          ],
          receiverName: [
            {required: false, message: '请输入收货人姓名', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          receiverTel: [
            {required: false, message: '请输入收货人电话', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          receiverAddress: [
            {required: false, message: '请输入收货人地址', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
          evaluationName: [
            {required: false, message: '请输入订单评价', trigger: 'blur'},
          ],
          evaluationId: [
            {required: false, message: '请输入订单评价', trigger: 'blur'},
          ],
          employeeName: [
            {required: false, message: '请输入用户', trigger: 'blur'},
          ],
          employeeId: [
            {required: false, message: '请输入用户', trigger: 'blur'},
          ],
          remark: [
            {required: false, message: '请输入备注', trigger: 'blur'},
            {validator: validateString(0, 1000, /^.*$/, "输入的数据不正确，请检查"), trigger: 'blur'},
          ],
        },
        isSubmiting: false,
        order: {},
        orderId: null,
        pickerOptionsOrderTime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        pickerOptionsPaymentTime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        pickerOptionsUpdateTime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        pickerOptionsCreateDatetime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        pickerOptionsUpdateDatetime: {
          disabledDate(time) {
            //TODO: 请在此判断可以输入的日期范围,
            //return time.getTime() > Date.now();
            return false;
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        alerts: {
          remarks: [{title: "功能说明", content: "TODO: 请在这里加上功能说明"},],
          successes: [], //TODO:[{title:'消息内容'},]
          infos: [],
          warnings: [],
          errors: []
        },
      }
    },

    methods: {
      //返回上一页
      backPage() {
        window.history.go(-1);
      },
      addAlert(message, title, type) {
        //type 可选的值为:remarks,successes,infos,warnings,errors
        type = type ? type : "errors";
        type = this.alerts[type] ? type : "errors";
        title = title ? title : message;
        this.alerts[type].unshift({title: title, content: message});
      },
      removeAlert(title, type) {
        //type 可选的值为:remarks,successes,infos,warnings,errors
        type = type ? type : "errors";
        type = this.alerts[type] ? type : "errors";
        for (var i = this.alerts[type].length - 1; i >= 0; i--) {
          delete this.alerts[type][i]
        }
      },
      submitOrder() {
        var refs = this.$refs;
        refs['orderForm'].validate(valid => {
          if (valid) {
            if (this.order.eid)//编辑订单
            {
              this.updateOrder();
            } else//保存订单
            {
              this.saveOrder();
            }
          } else {
            return false
          }
        })
      },
      saveOrder()//保存订单
      {
        this.order.name=this.order.orderCode;
        this.isSubmiting = true;
        this.buttonRequestProgressStart("正在保存,请稍后...");
        OrderService.saveOrder(this.order).then((resp) => {
          this.buttonRequestProgressClose();
          this.isSubmiting = false;
          var router = this.$router;
          router.push({path: '/simple/order/order'})
        }).catch((error) => {
          this.buttonRequestProgressClose();
          //error的data属性是后台传入的数据,data的extendedData存有后台传入的数据
          this.isSubmiting = false;

          this.addAlert({title: error.data.message})
          this.$message({
            type: 'error',
            message: '保存出错,原因是：' + error.data.message
          })
        })
      },
      updateOrder()//编辑订单
      {
        this.order.name=this.order.orderCode;
        this.isSubmiting = true;
        this.buttonRequestProgressStart("正在更新,请稍后...");
        OrderService.updateOrder(this.order).then((resp) => {
          this.buttonRequestProgressClose();
          this.isSubmiting = false;
          var router = this.$router;
          router.push({path: '/simple/order/order'})
        }).catch((error) => {
          this.buttonRequestProgressClose();
          //error的data属性是后台传入的数据,data的extendedData存有后台传入的数据
          this.isSubmiting = false;
          this.addAlert({title: error.data.message})
          this.$message({
            type: 'error',
            message: '保存出错,原因是：' + error.data.message
          })

        })
      },
      findOrderForEdit(orderId)//查找订单
      {
        OrderService.findOrderForEdit(orderId).then((resp) => {
          this.prepareForEdit(resp.data);
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '查询订单出错'
          })
        })
      },
      createOrder()//创建新的订单
      {
        OrderService.createOrder().then((resp) => {
          this.prepareForEdit(resp.data);
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: '创建新的订单出错'
          })
        })
      },
      prepareForEdit(orderEditDto) {
        this.order = orderEditDto.order;

        this.orderStatusCodeTables = orderEditDto.orderStatusCodeTables;
        this.businessBusinesss = orderEditDto.businessBusinesss
        this.evaluationEvaluations = orderEditDto.evaluationEvaluations
        this.employeeEmployees = orderEditDto.employeeEmployees
      },
      searchOrderStatus(queryString, cb) {
        var orderStatusCodeTables = this.orderStatusCodeTables;
        var results = queryString ? orderStatusCodeTables.filter(this.createFilterOrderStatus(queryString)) : orderStatusCodeTables;
        cb(results);
      },
      createFilterOrderStatus(queryString) {
        return (OrderStatus) => {
          return (OrderStatus.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },


      searchBusinessName(queryString, cb) {
        var businessBusinesss = this.businessBusinesss;

        //如果不为空，说明在加载页面的时候已经加载了所有的外键数据，否则表示没加载，则根据输入的信息从后台加载
        if (businessBusinesss) {
          var results = queryString ? businessBusinesss.filter(this.createFilterBusinessName(queryString)) : businessBusinesss;
          cb(results);
        } else {
          var results = d4utils.getObjectCached("findBusinesssWithIdNameByName_" + queryString);
          if (results) {
            cb(results);
          } else {
            var cb1 = cb;
            BusinessService.findBusinesssWithIdNameByName(queryString).then((resp) => {
              if (resp.data) {
                var results = resp.data;
                d4utils.cacheObject("findBusinesssWithIdNameByName_" + queryString);
                cb1(results)
              } else {
                this.$message({
                  type: 'error',
                  message: '没有查询到引用数据'
                });
              }
            }).catch((error) => {
              this.$message({
                type: 'error',
                message: '查询引用数据出错'
              })
            });
          }
        }
      },
      createFilterBusinessName(queryString) {
        return (business) => {
          return (business.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },
      handleSelectBusinessName(item) {
        this.order.businessId = item.eid;
      },

      searchEvaluationName(queryString, cb) {
        var evaluationEvaluations = this.evaluationEvaluations;

        //如果不为空，说明在加载页面的时候已经加载了所有的外键数据，否则表示没加载，则根据输入的信息从后台加载
        if (evaluationEvaluations) {
          var results = queryString ? evaluationEvaluations.filter(this.createFilterEvaluationName(queryString)) : evaluationEvaluations;
          cb(results);
        } else {
          var results = d4utils.getObjectCached("findEvaluationsWithIdNameByName_" + queryString);
          if (results) {
            cb(results);
          } else {
            var cb1 = cb;
            EvaluationService.findEvaluationsWithIdNameByName(queryString).then((resp) => {
              if (resp.data) {
                var results = resp.data;
                d4utils.cacheObject("findEvaluationsWithIdNameByName_" + queryString);
                cb1(results)
              } else {
                this.$message({
                  type: 'error',
                  message: '没有查询到引用数据'
                });
              }
            }).catch((error) => {
              this.$message({
                type: 'error',
                message: '查询引用数据出错'
              })
            });
          }
        }
      },
      createFilterEvaluationName(queryString) {
        return (evaluation) => {
          return (evaluation.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },
      handleSelectEvaluationName(item) {
        this.order.evaluationId = item.eid;
      },

      searchEmployeeName(queryString, cb) {
        var employeeEmployees = this.employeeEmployees;

        //如果不为空，说明在加载页面的时候已经加载了所有的外键数据，否则表示没加载，则根据输入的信息从后台加载
        if (employeeEmployees) {
          var results = queryString ? employeeEmployees.filter(this.createFilterEmployeeName(queryString)) : employeeEmployees;
          cb(results);
        } else {
          var results = d4utils.getObjectCached("findEmployeesWithIdNameByName_" + queryString);
          if (results) {
            cb(results);
          } else {
            var cb1 = cb;
            EmployeeService.findEmployeesWithIdNameByName(queryString).then((resp) => {
              if (resp.data) {
                var results = resp.data;
                d4utils.cacheObject("findEmployeesWithIdNameByName_" + queryString);
                cb1(results)
              } else {
                this.$message({
                  type: 'error',
                  message: '没有查询到引用数据'
                });
              }
            }).catch((error) => {
              this.$message({
                type: 'error',
                message: '查询引用数据出错'
              })
            });
          }
        }
      },
      createFilterEmployeeName(queryString) {
        return (employee) => {
          return (employee.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
        };
      },
      handleSelectEmployeeName(item) {
        this.order.employeeId = item.eid;
      },
    },
    created() {
      this.orderId = this.$route.params.orderId;
      if (this.orderId)//编辑
      {
        this.findOrderForEdit(this.orderId);
      } else//新增
      {
        this.createOrder();
      }
    },
  }
</script>
<style scoped lang="scss">

</style>
